package com.reflex.method;

import com.reflex.dao.Cat;

import java.lang.reflect.Method;

/**
 * @Author: lizehui
 * @Description: 速度比较
 * @Date: 2022/11/18/14:30
 */
public class SpeedComparison {

    public static void main(String[] args) throws Exception{
        m1();
        m2();
        m3();
    }

    //传统，用类调用方法
    public static void m1(){

        Cat cat = new Cat();
        long start = System.currentTimeMillis();
        for (int i = 0; i < 900000000; i++) {
            cat.speed();
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start + "ms - 传统，用类调用方法");
    }

    //通过反射，用类调用方法
    public static void m2() throws Exception {

        Class cls = Class.forName("com.reflex.dao.Cat");
        Object o = cls.newInstance();
        Method method = cls.getMethod("speed");
        long start = System.currentTimeMillis();
        for (int i = 0; i < 900000000; i++) {
            method.invoke(o);
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start + "ms - 通过反射，用类调用方法");
    }

    //通过反射，用类调用方法-关闭访问检查
    public static void m3() throws Exception {

        Class cls = Class.forName("com.reflex.dao.Cat");
        Object o = cls.newInstance();
        Method method = cls.getMethod("speed");
        //关闭访问检查
        method.setAccessible(true);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 900000000; i++) {
            method.invoke(o);
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start + "ms - 通过反射，用类调用方法-关闭访问检查");
    }
}
